package main

import (
	"bufio"
	"fmt"
	"net"
	"net/http"
	"strings"
)

var tokenLen = 6

var Conns = make(map[string]net.Conn)

// 长连接
func tcpHander(conn net.Conn) {
	var buf = make([]byte, tokenLen)
	if n, err := conn.Read(buf); n != 6 || err != nil {
		conn.Write([]byte("token解析失败!"))
		conn.Close()
		fmt.Println("token解析失败!")
		return
	}

	var token = string(buf)

	Conns[token] = conn

	// defer func() {
	// 	conn.Close()
	// 	delete(Conns, token)
	// }()

}

func tcpServer() {
	listen, err := net.Listen("tcp", "127.0.0.1:9002")
	if err != nil {
		fmt.Println(err)
		return
	}

	defer listen.Close() //延时关闭 listen

	for {
		conn, err := listen.Accept()
		fmt.Println("新的连接")
		if err != nil {
			fmt.Println(err)
			continue
		}
		go tcpHander(conn)
	}
}

var mylock = make(chan int, 1)

func main() {

	go tcpServer()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

		mylock <- 1

		var h = strings.Split(r.Host, ".")
		fmt.Println(r.Host, h)
		var subname = h[0]

		conn2, ok := Conns[subname]
		if !ok {
			w.Write([]byte("该链接未注册：" + subname))
			<-mylock
			return
		}

		if err := r.WriteProxy(conn2); err != nil {
			delete(Conns, subname)
			w.Write([]byte("客户端 tcp 连接已断开：" + subname))
			<-mylock
			return
		}

		hj, _ := w.(http.Hijacker)

		conn, _, err := hj.Hijack()
		if err != nil {
			w.Write([]byte("服务器异常 hijack：" + err.Error()))
			<-mylock
			return
		}

		defer conn.Close()

		response, err := http.ReadResponse(bufio.NewReader(conn2), r)

		if err != nil {
			fmt.Println(err)
			<-mylock
			return
		}

		if err := response.Write(conn); err != nil {
			fmt.Println(err)
		}
		// rw.Flush()
		// fmt.Println(response.Body)

		// if err := response.Write(os.Stdout); err != nil {
		// 	fmt.Println(err)
		// 	response.Body.Close()
		// }

		// conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
		// buf.WriteString("hello hijack\n")
		// buf.Flush()
		fmt.Println("======== http结束 ==========")
		<-mylock
	})

	http.ListenAndServe("127.0.0.1:9001", nil)

}
